﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.Threading;
using ResourceLoadBalancer.WebServices.Contracts.Data;
using System.Net;
using System.IO;

namespace ResourceLoadBalancer.Client
{
    public class SharePointScanner : FileScanner
    {
        IList<SPFile> filesInfo = null;
        private static string SHAREPOINT_QUEUE_TYPE = "SharePoint";

        public SharePointScanner()
        {
            filesInfo = new List<SPFile>();
            
        }
        
        public IList<SPFile> FilesInfo
        {
            get { return filesInfo; }
            set { filesInfo = value; }
        }

        public void ConfigureQueuing(string queueName)
        {
            base.ConfigureQueuing(SHAREPOINT_QUEUE_TYPE, queueName);
        }

        

        public void GetFiles(string url)
        {
            SPSite siteCollection = new SPSite(url);
            SPWebCollection webCollection = siteCollection.AllWebs;
            SharePointURIDataContract resourceURI = new SharePointURIDataContract();

            foreach (SPWeb web in webCollection)
            {
                Console.WriteLine("Web:" + web.Url);
                foreach (SPList list in web.Lists)
                {
                    Console.WriteLine("List:" + list.Title);
                    try
                    {
                        if (list.BaseType == SPBaseType.DocumentLibrary &&
                            list.Hidden != true)
                        {
                            foreach (SPListItem listItem in list.Items)
                            {
                                Console.WriteLine("Item adding to scan:" + listItem.Url);
                                resourceURI.DocumentURL = listItem["EncodedAbsUrl"].ToString();
                                resourceURI.SiteCollectionURL = url;
                                resourceURI.WebURL = web.ServerRelativeUrl;
                                QueueResourceURI(resourceURI);
                                
                                //filesInfo.Add(listItem.File);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }

                }
            }
        }

        public void QueueResourceURI(SharePointURIDataContract resourceURI)
        {
            serviceClient.QueueSharePointResourceURI(resourceURI);
        }

        public void ScanResources(string path)
        {
            //MD5Utility md5Utility = new MD5Utility();

            GetFiles(path);

            //foreach (SPFile file in FilesInfo)
            ////{

            ////Parallel.ForEach(FilesInfo, file =>
            //{
            //    ResourceURIDataContract resourceURI = new ResourceURIDataContract();

            //    string fullUrl = file.Item["EncodedAbsUrl"].ToString();

            //    try
            //    {
            //        ResourceDataContract resource = md5Utility.CalculateMD5Hash(file.OpenBinary());
            //        //ResourceDataContract resource = md5Utility.CalculateMD5Hash(DownloadFile(fullUrl));
            //        //ResourceDataContract resource = md5Utility.CalculateMD5Hash(file.OpenBinary());

            //        resourceURI.ResourceHash = resource.Hash;
            //        resourceURI.URI = fullUrl;
            //        resourceURI.HostName = hostName;
            //        resourceURI.URIHash = md5Utility.CalculateMD5Hash(file.Url);
            //        resourceURI.Owner = file.ModifiedBy.LoginName;
            //        resourceURI.LastModifiedDate = file.TimeLastModified;
            //        resourceURI.CreatedDate = file.TimeCreated;
            //        resourceURI.InventoryDate = DateTime.Now;
                    

            //        if (resource.Hash != "Unable to access file")
            //            Resources.Add(resource);

            //        if (resourceURI.ResourceHash != "Unable to access file")
            //            ResourcesURI.Add(resourceURI);

            //    }
            //    catch (Exception ex)
            //    {
            //        Console.WriteLine("An exception was encountered for the URL: " + fullUrl);
            //        Console.WriteLine(ex.Message);
            //    }
            //};
        }

        public byte[] DownloadFile(string url)
        {
            byte[] data = null;
            WebClient webClient = new WebClient();
            webClient.Credentials = CredentialCache.DefaultNetworkCredentials;

            //HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            //request.Credentials = CredentialCache.DefaultCredentials;
            
            try
            {
                Console.WriteLine("Downloading: " + url);
                data = webClient.DownloadData(url);
                //HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                //if (response.StatusCode == HttpStatusCode.OK &&
                //    response.ContentLength > 0)
                //{
                //    Stream streamResponse = response.GetResponseStream();
                //    StreamReader streamRead = new StreamReader(streamResponse);
                //    data = Encoding.UTF8.GetBytes(streamRead.ReadToEnd());

                //    // Close the stream object.
                //    streamResponse.Close();
                //    streamRead.Close();
                //}

                // Release the HttpWebResponse.
                //response.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("An exception was encountered for the URL: " + url);
                Console.WriteLine(ex.Message);
            }
            return data;
        }
    }
}
